package com.yuanian.wf.pojo.model;

import com.yuanian.wf.annotation.ProcessKey;
import com.yuanian.wf.context.spring.ApplicationContext;
import com.yuanian.wf.event.Event;
import com.yuanian.wf.exception.WfException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理所有ProcessKey的类
 */
public class ProcessManager {

    private static final Map<String, com.yuanian.wf.pojo.model.ProcessKey> processMap = new HashMap<>();

    public static String addProcess(Class clz) {
        if (clz.isAnnotationPresent(ProcessKey.class)) {
            ProcessKey wfProcessKey = (ProcessKey) clz.getAnnotation(ProcessKey.class);
            String processKey = wfProcessKey.value();
            if (processKey == null || processKey.trim().length() == 0) {
                throw new WfException("工作流初始化失败，processKey不能为空");
            }
            if (processMap.containsKey(processKey)) {
                throw new WfException("工作流初始化失败，" + processKey + "已经存在");
            }
            com.yuanian.wf.pojo.model.ProcessKey process = new com.yuanian.wf.pojo.model.ProcessKey(processKey, clz);
            processMap.put(processKey, process);
            return processKey;
        }
        return null;
    }

    public static void invoke(String processkey, String taskKey, Event event) throws InvocationTargetException, IllegalAccessException {
        //获取listener对象
        Object obj = ApplicationContext.getBean("wf" + "$" + processkey);
        com.yuanian.wf.pojo.model.ProcessKey processKey = getProcess(processkey);
        if (processKey == null) {
            return;
        }
        ProcessAction processAction = null;
        //获取对应的方法
        if (taskKey != null && taskKey.trim().length() != 0) {
            processAction = processKey.getProcessAction(event.getClass().getSimpleName() + "$" + taskKey);
        } else {
            processAction = processKey.getProcessAction(event.getClass().getSimpleName());
        }
        if (processAction != null) {
            try {
                //获取listener对象对应的方法
                processAction.invoke(obj, event);
            } catch (Exception e) {
                e.printStackTrace();
                throw new WfException(e.getMessage());
            }
        }
    }

    public static com.yuanian.wf.pojo.model.ProcessKey getProcess(String processKey) {
        return processMap.get(processKey);
    }
}
